home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlsub.Z / perlsub
Encoding:
Text File  |  1998-10-28  |  56.9 KB  |  1,717 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlsub - Perl subroutines
  10.  
  11.      SSSSYYYYNNNNOOOOPPPPSSSSIIIISSSS
  12.       To declare subroutines:
  13.  
  14.           sub NAME;            # A    "forward" declaration.
  15.           sub NAME(PROTO);        #  ditto, but with prototypes
  16.  
  17.           sub NAME BLOCK        # A    declaration and    a definition.
  18.           sub NAME(PROTO) BLOCK #  ditto, but with prototypes
  19.  
  20.       To define an anonymous subroutine at runtime:
  21.  
  22.           $subref =    sub BLOCK;          #    no proto
  23.           $subref =    sub (PROTO) BLOCK;    #    with proto
  24.  
  25.       To import subroutines:
  26.  
  27.           use PACKAGE qw(NAME1 NAME2 NAME3);
  28.  
  29.       To call subroutines:
  30.  
  31.           NAME(LIST);    # & is optional with parentheses.
  32.           NAME LIST;     # Parentheses optional if predeclared/imported.
  33.           &NAME;         # Makes current @_    visible    to called subroutine.
  34.  
  35.  
  36.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  37.       Like many languages, Perl provides for user-defined
  38.       subroutines.    These may be located anywhere in the main
  39.       program, loaded in from other    files via the do, require, or
  40.       use keywords,    or even    generated on the fly using eval    or
  41.       anonymous subroutines    (closures).  You can even call a
  42.       function indirectly using a variable containing its name or
  43.       a CODE reference to it.
  44.  
  45.       The Perl model for function call and return values is
  46.       simple: all functions    are passed as parameters one single
  47.       flat list of scalars,    and all    functions likewise return to
  48.       their    caller one single flat list of scalars.     Any arrays or
  49.       hashes in these call and return lists    will collapse, losing
  50.       their    identities--but    you may    always use pass-by-reference
  51.       instead to avoid this.  Both call and    return lists may
  52.       contain as many or as    few scalar elements as you'd like.
  53.       (Often a function without an explicit    return statement is
  54.       called a subroutine, but there's really no difference    from
  55.       the language's perspective.)
  56.  
  57.       Any arguments    passed to the routine come in as the array @_.
  58.       Thus if you called a function    with two arguments, those
  59.       would    be stored in $_[0] and $_[1].  The array @_ is a local
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  71.  
  72.  
  73.  
  74.       array, but its elements are aliases for the actual scalar
  75.       parameters.  In particular, if an element $_[0] is updated,
  76.       the corresponding argument is    updated    (or an error occurs if
  77.       it is    not updatable).     If an argument    is an array or hash
  78.       element which    did not    exist when the function    was called,
  79.       that element is created only when (and if) it    is modified or
  80.       if a reference to it is taken.  (Some    earlier    versions of
  81.       Perl created the element whether or not it was assigned to.)
  82.       Note that assigning to the whole array @_ removes the
  83.       aliasing, and    does not update    any arguments.
  84.  
  85.       The return value of the subroutine is    the value of the last
  86.       expression evaluated.     Alternatively,    a return statement may
  87.       be used to exit the subroutine, optionally specifying    the
  88.       returned value, which    will be    evaluated in the appropriate
  89.       context (list, scalar, or void) depending on the context of
  90.       the subroutine call.    If you specify no return value,    the
  91.       subroutine will return an empty list in a list context, an
  92.       undefined value in a scalar context, or nothing in a void
  93.       context.  If you return one or more arrays and/or hashes,
  94.       these    will be    flattened together into    one large
  95.       indistinguishable list.
  96.  
  97.       Perl does not    have named formal parameters, but in practice
  98.       all you do is    assign to a my() list of these.     Any variables
  99.       you use in the function that aren't declared private are
  100.       global variables.  For the gory details on creating private
  101.       variables, see the section on    _P_r_i_v_a_t_e    _V_a_r_i_a_b_l_e_s _v_i_a _m_y() and
  102.       the section on _T_e_m_p_o_r_a_r_y _V_a_l_u_e_s _v_i_a _l_o_c_a_l().    To create
  103.       protected environments for a set of functions    in a separate
  104.       package (and probably    a separate file), see the section on
  105.       _P_a_c_k_a_g_e_s in the _p_e_r_l_m_o_d manpage.
  106.  
  107.       Example:
  108.  
  109.           sub max {
  110.           my $max = shift(@_);
  111.           foreach $foo (@_) {
  112.               $max = $foo if $max < $foo;
  113.           }
  114.           return $max;
  115.           }
  116.           $bestday = max($mon,$tue,$wed,$thu,$fri);
  117.  
  118.       Example:
  119.  
  120.           #    get a line, combining continuation lines
  121.           #     that start with whitespace
  122.  
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  137.  
  138.  
  139.  
  140.           sub get_line {
  141.           $thisline = $lookahead;  # GLOBAL VARIABLES!!
  142.           LINE:    while (defined($lookahead = <STDIN>)) {
  143.               if ($lookahead =~    /^[ \t]/) {
  144.               $thisline .= $lookahead;
  145.               }
  146.               else {
  147.               last LINE;
  148.               }
  149.           }
  150.           $thisline;
  151.           }
  152.  
  153.           $lookahead = <STDIN>;      # get    first line
  154.           while ($_    = get_line()) {
  155.           ...
  156.           }
  157.  
  158.       Use array assignment to a local list to name your formal
  159.       arguments:
  160.  
  161.           sub maybeset {
  162.           my($key, $value) = @_;
  163.           $Foo{$key} = $value unless $Foo{$key};
  164.           }
  165.  
  166.       This also has    the effect of turning call-by-reference    into
  167.       call-by-value, because the assignment    copies the values.
  168.       Otherwise a function is free to do in-place modifications of
  169.       @_ and change    its caller's values.
  170.  
  171.           upcase_in($v1, $v2);  # this changes $v1 and $v2
  172.           sub upcase_in {
  173.           for (@_) { tr/a-z/A-Z/ }
  174.           }
  175.  
  176.       You aren't allowed to    modify constants in this way, of
  177.       course.  If an argument were actually    literal    and you    tried
  178.       to change it,    you'd take a (presumably fatal)    exception.
  179.       For example, this won't work:
  180.  
  181.           upcase_in("frederick");
  182.  
  183.       It would be much safer if the    upcase_in() function were
  184.       written to return a copy of its parameters instead of
  185.       changing them    in place:
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  203.  
  204.  
  205.  
  206.           ($v3, $v4) = upcase($v1, $v2);  #    this doesn't
  207.           sub upcase {
  208.           return unless    defined    wantarray;  # void context, do nothing
  209.           my @parms = @_;
  210.           for (@parms) { tr/a-z/A-Z/ }
  211.           return wantarray ? @parms : $parms[0];
  212.           }
  213.  
  214.       Notice how this (unprototyped) function doesn't care whether
  215.       it was passed    real scalars or    arrays.     Perl will see
  216.       everything as    one big    long flat @_ parameter list.  This is
  217.       one of the ways where    Perl's simple argument-passing style
  218.       shines.  The upcase()    function would work perfectly well
  219.       without changing the upcase()    definition even    if we fed it
  220.       things like this:
  221.  
  222.           @newlist     = upcase(@list1, @list2);
  223.           @newlist     = upcase( split /:/, $var );
  224.  
  225.       Do not, however, be tempted to do this:
  226.  
  227.           (@a, @b)     = upcase(@list1, @list2);
  228.  
  229.       Because like its flat    incoming parameter list, the return
  230.       list is also flat.  So all you have managed to do here is
  231.       stored everything in @a and made @b an empty list.  See the
  232.       section on _P_a_s_s _b_y _R_e_f_e_r_e_n_c_e for alternatives.
  233.  
  234.       A subroutine may be called using the "&" prefix.  The    "&" is
  235.       optional in modern Perls, and    so are the parentheses if the
  236.       subroutine has been predeclared.  (Note, however, that the
  237.       "&" is _N_O_T optional when you're just naming the subroutine,
  238.       such as when it's used as an argument    to defined() or
  239.       undef().  Nor    is it optional when you    want to    do an indirect
  240.       subroutine call with a subroutine name or reference using
  241.       the &$subref() or &{$subref}() constructs.  See the _p_e_r_l_r_e_f
  242.       manpage for more on that.)
  243.  
  244.       Subroutines may be called recursively.  If a subroutine is
  245.       called using the "&" form, the argument list is optional,
  246.       and if omitted, no @_    array is set up    for the    subroutine:
  247.       the @_ array at the time of the call is visible to
  248.       subroutine instead.  This is an efficiency mechanism that
  249.       new users may    wish to    avoid.
  250.  
  251.           &foo(1,2,3);      # pass three arguments
  252.           foo(1,2,3);      # the    same
  253.  
  254.           foo();          # pass a null    list
  255.           &foo();          # the    same
  256.  
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  269.  
  270.  
  271.  
  272.           &foo;          # foo() get current args, like foo(@_) !!
  273.           foo;          # like foo() IFF sub foo predeclared,    else "foo"
  274.  
  275.       Not only does    the "&"    form make the argument list optional,
  276.       but it also disables any prototype checking on the arguments
  277.       you do provide.  This    is partly for historical reasons, and
  278.       partly for having a convenient way to    cheat if you know what
  279.       you're doing.     See the section on Prototypes below.
  280.  
  281.       Function whose names are in all upper    case are reserved to
  282.       the Perl core, just as are modules whose names are in    all
  283.       lower    case.  A function in all capitals is a loosely-held
  284.       convention meaning it    will be    called indirectly by the run-
  285.       time system itself.  Functions that do special, pre-defined
  286.       things are BEGIN, END, AUTOLOAD, and DESTROY--plus all the
  287.       functions mentioned in the _p_e_r_l_t_i_e manpage.  The 5.005
  288.       release adds INIT to this list.
  289.  
  290.       PPPPrrrriiiivvvvaaaatttteeee VVVVaaaarrrriiiiaaaabbbblllleeeessss vvvviiiiaaaa    mmmmyyyy(((())))
  291.  
  292.       Synopsis:
  293.  
  294.           my $foo;          # declare $foo lexically local
  295.           my (@wid,    %get);      # declare list of variables local
  296.           my $foo =    "flurp";  # declare $foo lexical, and init it
  297.           my @oof =    @bar;      # declare @oof lexical, and init it
  298.  
  299.       A "my" declares the listed variables to be confined
  300.       (lexically) to the enclosing block, conditional
  301.       (if/unless/elsif/else), loop
  302.       (for/foreach/while/until/continue), subroutine, eval,    or
  303.       do/require/use'd file.  If more than one value is listed,
  304.       the list must    be placed in parentheses.  All listed elements
  305.       must be legal    lvalues.  Only alphanumeric identifiers    may be
  306.       lexically scoped--magical builtins like $/ must currently be
  307.       localize with    "local"    instead.
  308.  
  309.       Unlike dynamic variables created by the "local" operator,
  310.       lexical variables declared with "my" are totally hidden from
  311.       the outside world, including any called subroutines (even if
  312.       it's the same    subroutine called from itself or elsewhere--
  313.       every    call gets its own copy).
  314.  
  315.       This doesn't mean that a my()    variable declared in a
  316.       statically _e_n_c_l_o_s_i_n_g lexical scope would be invisible.  Only
  317.       the dynamic scopes are cut off.   For    example, the bumpx()
  318.       function below has access to the lexical $x variable because
  319.       both the my and the sub occurred at the same scope,
  320.       presumably the file scope.
  321.  
  322.           my $x = 10;
  323.           sub bumpx    { $x++ }
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  335.  
  336.  
  337.  
  338.       (An eval(), however, can see the lexical variables of    the
  339.       scope    it is being evaluated in so long as the    names aren't
  340.       hidden by declarations within    the eval() itself.  See    the
  341.       _p_e_r_l_r_e_f manpage.)
  342.  
  343.       The parameter    list to    my() may be assigned to    if desired,
  344.       which    allows you to initialize your variables.  (If no
  345.       initializer is given for a particular    variable, it is
  346.       created with the undefined value.)  Commonly this is used to
  347.       name the parameters to a subroutine.    Examples:
  348.  
  349.           $arg = "fred";        # "global" variable
  350.           $n = cube_root(27);
  351.           print "$arg thinks the root is $n\n";
  352.        fred    thinks the root    is 3
  353.  
  354.           sub cube_root {
  355.           my $arg = shift;  # name doesn't matter
  356.           $arg **= 1/3;
  357.           return $arg;
  358.           }
  359.  
  360.       The "my" is simply a modifier    on something you might assign
  361.       to.  So when you do assign to    the variables in its argument
  362.       list,    the "my" doesn't change    whether    those variables    are
  363.       viewed as a scalar or    an array.  So
  364.  
  365.           my ($foo)    = <STDIN>;          # WRONG?
  366.           my @FOO =    <STDIN>;
  367.  
  368.       both supply a    list context to    the right-hand side, while
  369.  
  370.           my $foo =    <STDIN>;
  371.  
  372.       supplies a scalar context.  But the following    declares only
  373.       one variable:
  374.  
  375.           my $foo, $bar = 1;          # WRONG
  376.  
  377.       That has the same effect as
  378.  
  379.           my $foo;
  380.           $bar = 1;
  381.  
  382.       The declared variable    is not introduced (is not visible)
  383.       until    after the current statement.  Thus,
  384.  
  385.           my $x = $x;
  386.  
  387.       can be used to initialize the    new $x with the    value of the
  388.       old $x, and the expression
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  401.  
  402.  
  403.  
  404.           my $x = 123 and $x == 123
  405.  
  406.       is false unless the old $x happened to have the value    123.
  407.  
  408.       Lexical scopes of control structures are not bounded
  409.       precisely by the braces that delimit their controlled
  410.       blocks; control expressions are part of the scope, too.
  411.       Thus in the loop
  412.  
  413.           while (defined(my    $line =    <>)) {
  414.           $line    = lc $line;
  415.           }    continue {
  416.           print    $line;
  417.           }
  418.  
  419.       the scope of $line extends from its declaration throughout
  420.       the rest of the loop construct (including the    continue
  421.       clause), but not beyond it.  Similarly, in the conditional
  422.  
  423.           if ((my $answer =    <STDIN>) =~ /^yes$/i) {
  424.           user_agrees();
  425.           }    elsif ($answer =~ /^no$/i) {
  426.           user_disagrees();
  427.           }    else {
  428.           chomp    $answer;
  429.           die "'$answer' is neither 'yes' nor 'no'";
  430.           }
  431.  
  432.       the scope of $answer extends from its    declaration throughout
  433.       the rest of the conditional (including elsif and else
  434.       clauses, if any), but    not beyond it.
  435.  
  436.       (None    of the foregoing applies to if/unless or while/until
  437.       modifiers appended to    simple statements.  Such modifiers are
  438.       not control structures and have no effect on scoping.)
  439.  
  440.       The foreach loop defaults to scoping its index variable
  441.       dynamically (in the manner of    local; see below).  However,
  442.       if the index variable    is prefixed with the keyword "my",
  443.       then it is lexically scoped instead.    Thus in    the loop
  444.  
  445.           for my $i    (1, 2, 3) {
  446.           some_function();
  447.           }
  448.  
  449.       the scope of $i extends to the end of    the loop, but not
  450.       beyond it, and so the    value of $i is unavailable in
  451.       some_function().
  452.  
  453.       Some users may wish to encourage the use of lexically    scoped
  454.       variables.  As an aid    to catching implicit references    to
  455.       package variables, if    you say
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  467.  
  468.  
  469.  
  470.           use strict 'vars';
  471.  
  472.       then any variable reference from there to the    end of the
  473.       enclosing block must either refer to a lexical variable, or
  474.       must be fully    qualified with the package name.  A
  475.       compilation error results otherwise.    An inner block may
  476.       countermand this with    "no strict 'vars'".
  477.  
  478.       A my() has both a compile-time and a run-time    effect.     At
  479.       compile time,    the compiler takes notice of it; the principle
  480.       usefulness of    this is    to quiet "use strict 'vars'".  The
  481.       actual initialization    is delayed until run time, so it gets
  482.       executed appropriately; every    time through a loop, for
  483.       example.
  484.  
  485.       Variables declared with "my" are not part of any package and
  486.       are therefore    never fully qualified with the package name.
  487.       In particular, you're    not allowed to try to make a package
  488.       variable (or other global) lexical:
  489.  
  490.           my $pack::var;      # ERROR!  Illegal syntax
  491.           my $_;          # also illegal (currently)
  492.  
  493.       In fact, a dynamic variable (also known as package or    global
  494.       variables) are still accessible using    the fully qualified ::
  495.       notation even    while a    lexical    of the same name is also
  496.       visible:
  497.  
  498.           package main;
  499.           local $x = 10;
  500.           my    $x = 20;
  501.           print "$x    and $::x\n";
  502.  
  503.       That will print out 20 and 10.
  504.  
  505.       You may declare "my" variables at the    outermost scope    of a
  506.       file to hide any such    identifiers totally from the outside
  507.       world.  This is similar to C's static    variables at the file
  508.       level.  To do    this with a subroutine requires    the use    of a
  509.       closure (anonymous function with lexical access).  If    a
  510.       block    (such as an eval(), function, or package) wants    to
  511.       create a private subroutine that cannot be called from
  512.       outside that block, it can declare a lexical variable
  513.       containing an    anonymous sub reference:
  514.  
  515.           my $secret_version = '1.001-beta';
  516.           my $secret_sub = sub { print $secret_version };
  517.           &$secret_sub();
  518.  
  519.       As long as the reference is never returned by    any function
  520.       within the module, no    outside    module can see the subroutine,
  521.       because its name is not in any package's symbol table.
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  533.  
  534.  
  535.  
  536.       Remember that    it's not _R_E_A_L_L_Y    called
  537.       $some_pack::secret_version or    anything; it's just
  538.       $secret_version, unqualified and unqualifiable.
  539.  
  540.       This does not    work with object methods, however; all object
  541.       methods have to be in    the symbol table of some package to be
  542.       found.
  543.  
  544.       PPPPeeeerrrriiiisssstttteeeennnntttt PPPPrrrriiiivvvvaaaatttteeee VVVVaaaarrrriiiiaaaabbbblllleeeessss
  545.  
  546.       Just because a lexical variable is lexically (also called
  547.       statically) scoped to    its enclosing block, eval, or do FILE,
  548.       this doesn't mean that within    a function it works like a C
  549.       static.  It normally works more like a C auto, but with
  550.       implicit garbage collection.
  551.  
  552.       Unlike local variables in C or C++, Perl's lexical variables
  553.       don't    necessarily get    recycled just because their scope has
  554.       exited.  If something    more permanent is still    aware of the
  555.       lexical, it will stick around.  So long as something else
  556.       references a lexical,    that lexical won't be freed--which is
  557.       as it    should be.  You    wouldn't want memory being free    until
  558.       you were done    using it, or kept around once you were done.
  559.       Automatic garbage collection takes care of this for you.
  560.  
  561.       This means that you can pass back or save away references to
  562.       lexical variables, whereas to    return a pointer to a C    auto
  563.       is a grave error.  It    also gives us a    way to simulate    C's
  564.       function statics.  Here's a mechanism    for giving a function
  565.       private variables with both lexical scoping and a static
  566.       lifetime.  If    you do want to create something    like C's
  567.       static variables, just enclose the whole function in an
  568.       extra    block, and put the static variable outside the
  569.       function but in the block.
  570.  
  571.           {
  572.           my $secret_val = 0;
  573.           sub gimme_another {
  574.               return ++$secret_val;
  575.           }
  576.           }
  577.           #    $secret_val now    becomes    unreachable by the outside
  578.           #    world, but retains its value between calls to gimme_another
  579.  
  580.       If this function is being sourced in from a separate file
  581.       via require or use, then this    is probably just fine.    If
  582.       it's all in the main program,    you'll need to arrange for the
  583.       my() to be executed early, either by putting the whole block
  584.       above    your main program, or more likely, placing merely a
  585.       BEGIN    sub around it to make sure it gets executed before
  586.       your program starts to run:
  587.  
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  599.  
  600.  
  601.  
  602.           sub BEGIN    {
  603.           my $secret_val = 0;
  604.           sub gimme_another {
  605.               return ++$secret_val;
  606.           }
  607.           }
  608.  
  609.       See the section on _P_a_c_k_a_g_e _C_o_n_s_t_r_u_c_t_o_r_s _a_n_d _D_e_s_t_r_u_c_t_o_r_s in
  610.       the _p_e_r_l_m_o_d manpage about the    BEGIN function.
  611.  
  612.       If declared at the outermost scope, the file scope, then
  613.       lexicals work    someone    like C's file statics.    They are
  614.       available to all functions in    that same file declared    below
  615.       them,    but are    inaccessible from outside of the file.    This
  616.       is sometimes used in modules to create private variables for
  617.       the whole module.
  618.  
  619.       TTTTeeeemmmmppppoooorrrraaaarrrryyyy VVVVaaaalllluuuueeeessss vvvviiiiaaaa _l_o_c_a_l()
  620.  
  621.       NNNNOOOOTTTTEEEE:    In general, you    should be using    "my" instead of
  622.       "local", because it's    faster and safer.  Exceptions to this
  623.       include the global punctuation variables, filehandles    and
  624.       formats, and direct manipulation of the Perl symbol table
  625.       itself.  Format variables often use "local" though, as do
  626.       other    variables whose    current    value must be visible to
  627.       called subroutines.
  628.  
  629.       Synopsis:
  630.  
  631.           local $foo;          # declare $foo dynamically local
  632.           local (@wid, %get);      # declare list of variables local
  633.           local $foo = "flurp";      # declare $foo dynamic, and init it
  634.           local @oof = @bar;      # declare @oof dynamic, and init it
  635.  
  636.           local *FH;          # localize $FH, @FH, %FH, &FH     ...
  637.           local *merlyn = *randal;      # now    $merlyn    is really $randal, plus
  638.                       #    @merlyn    is really @randal, etc
  639.           local *merlyn = 'randal';      # SAME THING:    promote    'randal' to *randal
  640.           local *merlyn = \$randal;      # just alias $merlyn,    not @merlyn etc
  641.  
  642.       A local() modifies its listed    variables to be    "local"    to the
  643.       enclosing block, eval, or do FILE--and to _a_n_y    _s_u_b_r_o_u_t_i_n_e
  644.       _c_a_l_l_e_d _f_r_o_m _w_i_t_h_i_n _t_h_a_t _b_l_o_c_k.  A local() just gives
  645.       temporary values to global (meaning package) variables.  It
  646.       does nnnnooootttt create a local variable.  This is known as dynamic
  647.       scoping.  Lexical scoping is done with "my", which works
  648.       more like C's    auto declarations.
  649.  
  650.       If more than one variable is given to    local(), they must be
  651.       placed in parentheses.  All listed elements must be legal
  652.       lvalues.  This operator works    by saving the current values
  653.       of those variables in    its argument list on a hidden stack
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  665.  
  666.  
  667.  
  668.       and restoring    them upon exiting the block, subroutine, or
  669.       eval.     This means that called    subroutines can    also reference
  670.       the local variable, but not the global one.  The argument
  671.       list may be assigned to if desired, which allows you to
  672.       initialize your local    variables.  (If    no initializer is
  673.       given    for a particular variable, it is created with an
  674.       undefined value.)  Commonly this is used to name the
  675.       parameters to    a subroutine.  Examples:
  676.  
  677.           for $i ( 0 .. 9 )    {
  678.           $digits{$i} =    $i;
  679.           }
  680.           #    assume this function uses global %digits hash
  681.           parse_num();
  682.  
  683.           #    now temporarily    add to %digits hash
  684.           if ($base12) {
  685.           # (NOTE: not claiming    this is    efficient!)
  686.           local    %digits     = (%digits, 't' => 10,    'e' => 11);
  687.           parse_num();    # parse_num gets this new %digits!
  688.           }
  689.           #    old %digits restored here
  690.  
  691.       Because local() is a run-time    command, it gets executed
  692.       every    time through a loop.  In releases of Perl previous to
  693.       5.0, this used more stack storage each time until the    loop
  694.       was exited.  Perl now    reclaims the space each    time through,
  695.       but it's still more efficient    to declare your    variables
  696.       outside the loop.
  697.  
  698.       A local is simply a modifier on an lvalue expression.     When
  699.       you assign to    a localized variable, the local    doesn't    change
  700.       whether its list is viewed as    a scalar or an array.  So
  701.  
  702.           local($foo) = <STDIN>;
  703.           local @FOO = <STDIN>;
  704.  
  705.       both supply a    list context to    the right-hand side, while
  706.  
  707.           local $foo = <STDIN>;
  708.  
  709.       supplies a scalar context.
  710.  
  711.       A note about local() and composite types is in order.
  712.       Something like local(%foo) works by temporarily placing a
  713.       brand    new hash in the    symbol table.  The old hash is left
  714.       alone, but is    hidden "behind"    the new    one.
  715.  
  716.       This means the old variable is completely invisible via the
  717.       symbol table (i.e. the hash entry in the *foo    typeglob) for
  718.       the duration of the dynamic scope within which the local()
  719.       was seen.  This has the effect of allowing one to
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  731.  
  732.  
  733.  
  734.       temporarily occlude any magic    on composite types.  For
  735.       instance, this will briefly alter a tied hash    to some    other
  736.       implementation:
  737.  
  738.           tie %ahash, 'APackage';
  739.           [...]
  740.           {
  741.          local %ahash;
  742.          tie %ahash, 'BPackage';
  743.          [..called code    will see %ahash    tied to    'BPackage'..]
  744.          {
  745.             local %ahash;
  746.             [..%ahash is a normal (untied) hash    here..]
  747.          }
  748.           }
  749.           [..%ahash    back to    its initial tied self again..]
  750.  
  751.       As another example, a    custom implementation of %ENV might
  752.       look like this:
  753.  
  754.           {
  755.           local    %ENV;
  756.           tie %ENV, 'MyOwnEnv';
  757.           [..do    your own fancy %ENV manipulation here..]
  758.           }
  759.           [..normal    %ENV behavior here..]
  760.  
  761.       It's also worth taking a moment to explain what happens when
  762.       you localize a member    of a composite type (i.e. an array or
  763.       hash element).  In this case,    the element is localized _b_y
  764.       _n_a_m_e.    This means that    when the scope of the local() ends,
  765.       the saved value will be restored to the hash element whose
  766.       key was named    in the local(),    or the array element whose
  767.       index    was named in the local().  If that element was deleted
  768.       while    the local() was    in effect (e.g.    by a delete() from a
  769.       hash or a shift() of an array), it will spring back into
  770.       existence, possibly extending    an array and filling in    the
  771.       skipped elements with    undef.    For instance, if you say
  772.  
  773.  
  774.  
  775.  
  776.  
  777.  
  778.  
  779.  
  780.  
  781.  
  782.  
  783.  
  784.  
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  797.  
  798.  
  799.  
  800.           %hash = (    'This' => 'is',    'a' => 'test' );
  801.           @ary  = (    0..5 );
  802.           {
  803.            local($ary[5]) = 6;
  804.            local($hash{'a'}) = 'drill';
  805.            while (my $e    = pop(@ary)) {
  806.                print "$e . . .\n";
  807.                last unless $e >    3;
  808.            }
  809.            if (@ary) {
  810.                $hash{'only a'} = 'test';
  811.                delete $hash{'a'};
  812.            }
  813.           }
  814.           print join(' ', map { "$_    $hash{$_}" } sort keys %hash),".\n";
  815.           print "The array has ",scalar(@ary)," elements: ",
  816.             join(', ', map { defined $_    ? $_ : 'undef' } @ary),"\n";
  817.  
  818.       Perl will print
  819.  
  820.           6    . . .
  821.           4    . . .
  822.           3    . . .
  823.           This is a    test only a test.
  824.           The array    has 6 elements:    0, 1, 2, undef,    undef, 5
  825.  
  826.  
  827.       PPPPaaaassssssssiiiinnnngggg SSSSyyyymmmmbbbboooollll TTTTaaaabbbblllleeee EEEEnnnnttttrrrriiiieeeessss ((((ttttyyyyppppeeeegggglllloooobbbbssss))))
  828.  
  829.       [Note:  The mechanism    described in this section was
  830.       originally the only way to simulate pass-by-reference    in
  831.       older    versions of Perl.  While it still works    fine in    modern
  832.       versions, the    new reference mechanism    is generally easier to
  833.       work with.  See below.]
  834.  
  835.       Sometimes you    don't want to pass the value of    an array to a
  836.       subroutine but rather    the name of it,    so that    the subroutine
  837.       can modify the global    copy of    it rather than working with a
  838.       local    copy.  In perl you can refer to    all objects of a
  839.       particular name by prefixing the name    with a star: *foo.
  840.       This is often    known as a "typeglob", because the star    on the
  841.       front    can be thought of as a wildcard    match for all the
  842.       funny    prefix characters on variables and subroutines and
  843.       such.
  844.  
  845.       When evaluated, the typeglob produces    a scalar value that
  846.       represents all the objects of    that name, including any
  847.       filehandle, format, or subroutine.  When assigned to,    it
  848.       causes the name mentioned to refer to    whatever "*" value was
  849.       assigned to it.  Example:
  850.  
  851.  
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  863.  
  864.  
  865.  
  866.           sub doubleary {
  867.           local(*someary) = @_;
  868.           foreach $elem    (@someary) {
  869.               $elem *= 2;
  870.           }
  871.           }
  872.           doubleary(*foo);
  873.           doubleary(*bar);
  874.  
  875.       Note that scalars are    already    passed by reference, so    you
  876.       can modify scalar arguments without using this mechanism by
  877.       referring explicitly to $_[0]    etc.  You can modify all the
  878.       elements of an array by passing all the elements as scalars,
  879.       but you have to use the * mechanism (or the equivalent
  880.       reference mechanism) to push,    pop, or    change the size    of an
  881.       array.  It will certainly be faster to pass the typeglob (or
  882.       reference).
  883.  
  884.       Even if you don't want to modify an array, this mechanism is
  885.       useful for passing multiple arrays in    a single LIST, because
  886.       normally the LIST mechanism will merge all the array values
  887.       so that you can't extract out    the individual arrays.    For
  888.       more on typeglobs, see the section on    _T_y_p_e_g_l_o_b_s _a_n_d
  889.       _F_i_l_e_h_a_n_d_l_e_s in the _p_e_r_l_d_a_t_a manpage.
  890.  
  891.       WWWWhhhheeeennnn ttttoooo SSSSttttiiiillllllll    UUUUsssseeee _l_o_c_a_l()
  892.  
  893.       Despite the existence    of my(), there are still three places
  894.       where    the local() operator still shines.  In fact, in    these
  895.       three    places,    you _m_u_s_t use local instead of my.
  896.  
  897.      especially    $_.
  898.       1. You need to give a    global variable    a temporary value,
  899.            The global variables, like @ARGV    or the punctuation
  900.            variables, must be localized with local().  This    block
  901.            reads in    /_e_t_c/_m_o_t_d, and splits it up into chunks
  902.            separated by lines of equal signs, which    are placed in
  903.            @Fields.
  904.  
  905.            {
  906.                local @ARGV = ("/etc/motd");
  907.                local $/    = undef;
  908.                local $_    = <>;
  909.                @Fields = split /^\s*=+\s*$/;
  910.            }
  911.  
  912.            It particular, it's important to    localize $_ in any
  913.            routine that assigns to it.  Look out for implicit
  914.            assignments in while conditionals.
  915.  
  916.      function.
  917.       2. You need to create    a local    file or    directory handle or a local
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  929.  
  930.  
  931.  
  932.            A function that needs a filehandle of its own must use
  933.            local() uses local() on complete    typeglob.   This can
  934.            be used to create new symbol table entries:
  935.  
  936.            sub ioqueue {
  937.                local  (*READER,    *WRITER);    # not my!
  938.                pipe    (READER,     WRITER);    or    die "pipe: $!";
  939.                return (*READER,    *WRITER);
  940.            }
  941.            ($head, $tail) = ioqueue();
  942.  
  943.            See the Symbol module for a way to create anonymous
  944.            symbol table entries.
  945.  
  946.            Because assignment of a reference to a typeglob creates
  947.            an alias, this can be used to create what is
  948.            effectively a local function, or    at least, a local
  949.            alias.
  950.  
  951.            {
  952.                local *grow = \&shrink; # only until this block exists
  953.                grow();               # really    calls shrink()
  954.                move();               # if move() grow()s, it shrink()s too
  955.            }
  956.            grow();               # get the real grow() again
  957.  
  958.            See the section on _F_u_n_c_t_i_o_n _T_e_m_p_l_a_t_e_s in    the _p_e_r_l_r_e_f
  959.            manpage for more    about manipulating functions by    name
  960.            in this way.
  961.  
  962.      hash.
  963.       3. You want to temporarily change just one element of    an array or
  964.            You can localize    just one element of an aggregate.
  965.            Usually this is done on dynamics:
  966.  
  967.            {
  968.                local $SIG{INT} = 'IGNORE';
  969.                funct();                   # uninterruptible
  970.            }
  971.            # interruptibility automatically restored here
  972.  
  973.            But it also works on lexically declared aggregates.
  974.            Prior to    5.005, this operation could on occasion
  975.            misbehave.
  976.  
  977.       PPPPaaaassssssss bbbbyyyy RRRReeeeffffeeeerrrreeeennnncccceeee
  978.  
  979.       If you want to pass more than    one array or hash into a
  980.       function--or return them from    it--and    have them maintain
  981.       their    integrity, then    you're going to    have to    use an
  982.       explicit pass-by-reference.  Before you do that, you need to
  983.       understand references    as detailed in the _p_e_r_l_r_e_f manpage.
  984.  
  985.  
  986.  
  987.      Page 15                        (printed 10/23/98)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  995.  
  996.  
  997.  
  998.       This section may not make much sense to you otherwise.
  999.  
  1000.       Here are a few simple    examples.  First, let's    pass in
  1001.       several arrays to a function and have    it pop all of then,
  1002.       return a new list of all their former    last elements:
  1003.  
  1004.           @tailings    = popmany ( \@a, \@b, \@c, \@d );
  1005.  
  1006.           sub popmany {
  1007.           my $aref;
  1008.           my @retlist =    ();
  1009.           foreach $aref    ( @_ ) {
  1010.               push @retlist, pop @$aref;
  1011.           }
  1012.           return @retlist;
  1013.           }
  1014.  
  1015.       Here's how you might write a function    that returns a list of
  1016.       keys occurring in all    the hashes passed to it:
  1017.  
  1018.           @common =    inter( \%foo, \%bar, \%joe );
  1019.           sub inter    {
  1020.           my ($k, $href, %seen); # locals
  1021.           foreach $href    (@_) {
  1022.               while ( $k = each    %$href ) {
  1023.               $seen{$k}++;
  1024.               }
  1025.           }
  1026.           return grep {    $seen{$_} == @_    } keys %seen;
  1027.           }
  1028.  
  1029.       So far, we're    using just the normal list return mechanism.
  1030.       What happens if you want to pass or return a hash?  Well, if
  1031.       you're using only one    of them, or you    don't mind them
  1032.       concatenating, then the normal calling convention is ok,
  1033.       although a little expensive.
  1034.  
  1035.       Where    people get into    trouble    is here:
  1036.  
  1037.           (@a, @b) = func(@c, @d);
  1038.       or
  1039.           (%a, %b) = func(%c, %d);
  1040.  
  1041.       That syntax simply won't work.  It sets just @a or %a    and
  1042.       clears the @b    or %b.    Plus the function didn't get passed
  1043.       into two separate arrays or hashes: it got one long list in
  1044.       @_, as always.
  1045.  
  1046.       If you can arrange for everyone to deal with this through
  1047.       references, it's cleaner code, although not so nice to look
  1048.       at.  Here's a    function that takes two    array references as
  1049.       arguments, returning the two array elements in order of how
  1050.  
  1051.  
  1052.  
  1053.      Page 16                        (printed 10/23/98)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1061.  
  1062.  
  1063.  
  1064.       many elements    they have in them:
  1065.  
  1066.           ($aref, $bref) = func(\@c, \@d);
  1067.           print "@$aref has    more than @$bref\n";
  1068.           sub func {
  1069.           my ($cref, $dref) = @_;
  1070.           if (@$cref > @$dref) {
  1071.               return ($cref, $dref);
  1072.           } else {
  1073.               return ($dref, $cref);
  1074.           }
  1075.           }
  1076.  
  1077.       It turns out that you    can actually do    this also:
  1078.  
  1079.           (*a, *b) = func(\@c, \@d);
  1080.           print "@a    has more than @b\n";
  1081.           sub func {
  1082.           local    (*c, *d) = @_;
  1083.           if (@c > @d) {
  1084.               return (\@c, \@d);
  1085.           } else {
  1086.               return (\@d, \@c);
  1087.           }
  1088.           }
  1089.  
  1090.       Here we're using the typeglobs to do symbol table aliasing.
  1091.       It's a tad subtle, though, and also won't work if you're
  1092.       using    my() variables,    because    only globals (well, and
  1093.       local()s) are    in the symbol table.
  1094.  
  1095.       If you're passing around filehandles,    you could usually just
  1096.       use the bare typeglob, like *STDOUT, but typeglobs
  1097.       references would be better because they'll still work
  1098.       properly under use strict 'refs'.  For example:
  1099.  
  1100.           splutter(\*STDOUT);
  1101.           sub splutter {
  1102.           my $fh = shift;
  1103.           print    $fh "her um well a hmmm\n";
  1104.           }
  1105.  
  1106.           $rec = get_rec(\*STDIN);
  1107.           sub get_rec {
  1108.           my $fh = shift;
  1109.           return scalar    <$fh>;
  1110.           }
  1111.  
  1112.       Another way to do this is using *HANDLE{IO}, see the _p_e_r_l_r_e_f
  1113.       manpage for usage and    caveats.
  1114.  
  1115.       If you're planning on    generating new filehandles, you    could
  1116.  
  1117.  
  1118.  
  1119.      Page 17                        (printed 10/23/98)
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1127.  
  1128.  
  1129.  
  1130.       do this:
  1131.  
  1132.           sub openit {
  1133.           my $name = shift;
  1134.           local    *FH;
  1135.           return open (FH, $path) ? *FH    : undef;
  1136.           }
  1137.  
  1138.       Although that    will actually produce a    small memory leak.
  1139.       See the bottom of the    open() entry in    the _p_e_r_l_f_u_n_c manpage
  1140.       for a    somewhat cleaner way using the IO::Handle package.
  1141.  
  1142.       PPPPrrrroooottttoooottttyyyyppppeeeessss
  1143.  
  1144.       As of    the 5.002 release of perl, if you declare
  1145.  
  1146.           sub mypush (\@@)
  1147.  
  1148.       then mypush()    takes arguments    exactly    like push() does.  The
  1149.       declaration of the function to be called must    be visible at
  1150.       compile time.     The prototype affects only the    interpretation
  1151.       of new-style calls to    the function, where new-style is
  1152.       defined as not using the & character.     In other words, if
  1153.       you call it like a builtin function, then it behaves like a
  1154.       builtin function.  If    you call it like an old-fashioned
  1155.       subroutine, then it behaves like an old-fashioned
  1156.       subroutine.  It naturally falls out from this    rule that
  1157.       prototypes have no influence on subroutine references    like
  1158.       \&foo    or on indirect subroutine calls    like &{$subref}.
  1159.  
  1160.       Method calls are not influenced by prototypes    either,
  1161.       because the function to be called is indeterminate at
  1162.       compile time,    because    it depends on inheritance.
  1163.  
  1164.       Because the intent is    primarily to let you define
  1165.       subroutines that work    like builtin commands, here are    the
  1166.       prototypes for some other functions that parse almost
  1167.       exactly like the corresponding builtins.
  1168.  
  1169.           Declared as          Called as
  1170.  
  1171.  
  1172.  
  1173.  
  1174.  
  1175.  
  1176.  
  1177.  
  1178.  
  1179.  
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.      Page 18                        (printed 10/23/98)
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1193.  
  1194.  
  1195.  
  1196.           sub mylink ($$)           mylink $old, $new
  1197.           sub myvec    ($$$)           myvec $var, $offset, 1
  1198.           sub myindex ($$;$)       myindex &getstring, "substr"
  1199.           sub mysyswrite ($$$;$)   mysyswrite $buf,    0, length($buf)    - $off,    $off
  1200.           sub myreverse (@)           myreverse $a, $b, $c
  1201.           sub myjoin ($@)           myjoin ":", $a, $b, $c
  1202.           sub mypop    (\@)           mypop @array
  1203.           sub mysplice (\@$$@)     mysplice    @array,    @array,    0, @pushme
  1204.           sub mykeys (\%)           mykeys %{$hashref}
  1205.           sub myopen (*;$)           myopen HANDLE, $name
  1206.           sub mypipe (**)           mypipe READHANDLE, WRITEHANDLE
  1207.           sub mygrep (&@)           mygrep {    /foo/ }    $a, $b,    $c
  1208.           sub myrand ($)           myrand 42
  1209.           sub mytime ()           mytime
  1210.  
  1211.       Any backslashed prototype character represents an actual
  1212.       argument that    absolutely must    start with that    character.
  1213.       The value passed to the subroutine (as part of @_) will be a
  1214.       reference to the actual argument given in the    subroutine
  1215.       call,    obtained by applying \ to that argument.
  1216.  
  1217.       Unbackslashed    prototype characters have special meanings.
  1218.       Any unbackslashed @ or % eats    all the    rest of    the arguments,
  1219.       and forces list context.  An argument    represented by $
  1220.       forces scalar    context.  An & requires    an anonymous
  1221.       subroutine, which, if    passed as the first argument, does not
  1222.       require the "sub" keyword or a subsequent comma.  A *    does
  1223.       whatever it has to do    to turn    the argument into a reference
  1224.       to a symbol table entry.
  1225.  
  1226.       A semicolon separates    mandatory arguments from optional
  1227.       arguments.  (It is redundant before @    or %.)
  1228.  
  1229.       Note how the last three examples above are treated specially
  1230.       by the parser.  mygrep() is parsed as    a true list operator,
  1231.       myrand() is parsed as    a true unary operator with unary
  1232.       precedence the same as rand(), and mytime() is truly without
  1233.       arguments, just like time().    That is, if you    say
  1234.  
  1235.           mytime +2;
  1236.  
  1237.       you'll get mytime() +    2, not mytime(2), which    is how it
  1238.       would    be parsed without the prototype.
  1239.  
  1240.       The interesting thing    about &    is that    you can    generate new
  1241.       syntax with it:
  1242.  
  1243.  
  1244.  
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.      Page 19                        (printed 10/23/98)
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1259.  
  1260.  
  1261.  
  1262.           sub try (&@) {
  1263.           my($try,$catch) = @_;
  1264.           eval { &$try };
  1265.           if ($@) {
  1266.               local $_ = $@;
  1267.               &$catch;
  1268.           }
  1269.           }
  1270.           sub catch    (&) { $_[0] }
  1271.  
  1272.           try {
  1273.           die "phooey";
  1274.           }    catch {
  1275.           /phooey/ and print "unphooey\n";
  1276.           };
  1277.  
  1278.       That prints "unphooey".  (Yes, there are still unresolved
  1279.       issues having    to do with the visibility of @_.  I'm ignoring
  1280.       that question    for the    moment.     (But note that    if we make @_
  1281.       lexically scoped, those anonymous subroutines    can act    like
  1282.       closures... (Gee, is this sounding a little Lispish?    (Never
  1283.       mind.))))
  1284.  
  1285.       And here's a reimplementation    of grep:
  1286.  
  1287.           sub mygrep (&@) {
  1288.           my $code = shift;
  1289.           my @result;
  1290.           foreach $_ (@_) {
  1291.               push(@result, $_)    if &$code;
  1292.           }
  1293.           @result;
  1294.           }
  1295.  
  1296.       Some folks would prefer full alphanumeric prototypes.
  1297.       Alphanumerics    have been intentionally    left out of prototypes
  1298.       for the express purpose of someday in    the future adding
  1299.       named, formal    parameters.  The current mechanism's main goal
  1300.       is to    let module writers provide better diagnostics for
  1301.       module users.     Larry feels the notation quite    understandable
  1302.       to Perl programmers, and that    it will    not intrude greatly
  1303.       upon the meat    of the module, nor make    it harder to read.
  1304.       The line noise is visually encapsulated into a small pill
  1305.       that's easy to swallow.
  1306.  
  1307.       It's probably    best to    prototype new functions, not retrofit
  1308.       prototyping into older ones.    That's because you must    be
  1309.       especially careful about silent impositions of differing
  1310.       list versus scalar contexts.    For example, if    you decide
  1311.       that a function should take just one parameter, like this:
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.      Page 20                        (printed 10/23/98)
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1325.  
  1326.  
  1327.  
  1328.           sub func ($) {
  1329.           my $n    = shift;
  1330.           print    "you gave me $n\n";
  1331.           }
  1332.  
  1333.       and someone has been calling it with an array    or expression
  1334.       returning a list:
  1335.  
  1336.           func(@foo);
  1337.           func( split /:/ );
  1338.  
  1339.       Then you've just supplied an automatic scalar() in front of
  1340.       their    argument, which    can be more than a bit surprising.
  1341.       The old @foo which used to hold one thing doesn't get    passed
  1342.       in.  Instead,    the func() now gets passed in 1, that is, the
  1343.       number of elements in    @foo.  And the split() gets called in
  1344.       a scalar context and starts scribbling on your @_ parameter
  1345.       list.
  1346.  
  1347.       This is all very powerful, of    course,    and should be used
  1348.       only in moderation to    make the world a better    place.
  1349.  
  1350.       CCCCoooonnnnssssttttaaaannnntttt FFFFuuuunnnnccccttttiiiioooonnnnssss
  1351.  
  1352.       Functions with a prototype of    () are potential candidates
  1353.       for inlining.     If the    result after optimization and constant
  1354.       folding is either a constant or a lexically-scoped scalar
  1355.       which    has no other references, then it will be used in place
  1356.       of function calls made without & or do. Calls    made using &
  1357.       or do    are never inlined.  (See _c_o_n_s_t_a_n_t._p_m for an easy way
  1358.       to declare most constants.)
  1359.  
  1360.       The following    functions would    all be inlined:
  1361.  
  1362.           sub pi ()          { 3.14159 }          # Not    exact, but close.
  1363.           sub PI ()          { 4 *    atan2 1, 1 }      # As good as it gets,
  1364.                               # and    it's inlined, too!
  1365.           sub ST_DEV ()      { 0 }
  1366.           sub ST_INO ()      { 1 }
  1367.  
  1368.           sub FLAG_FOO ()      { 1 << 8 }
  1369.           sub FLAG_BAR ()      { 1 << 9 }
  1370.           sub FLAG_MASK ()      { FLAG_FOO | FLAG_BAR    }
  1371.  
  1372.  
  1373.  
  1374.  
  1375.  
  1376.  
  1377.  
  1378.  
  1379.  
  1380.  
  1381.  
  1382.  
  1383.      Page 21                        (printed 10/23/98)
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1391.  
  1392.  
  1393.  
  1394.           sub OPT_BAZ ()      { not    (0x1B58    & FLAG_MASK) }
  1395.           sub BAZ_VAL () {
  1396.           if (OPT_BAZ) {
  1397.               return 23;
  1398.           }
  1399.           else {
  1400.               return 42;
  1401.           }
  1402.           }
  1403.  
  1404.           sub N () { int(BAZ_VAL) /    3 }
  1405.           BEGIN {
  1406.           my $prod = 1;
  1407.           for (1..N) { $prod *=    $_ }
  1408.           sub N_FACTORIAL () { $prod }
  1409.           }
  1410.  
  1411.       If you redefine a subroutine that was    eligible for inlining,
  1412.       you'll get a mandatory warning.  (You    can use    this warning
  1413.       to tell whether or not a particular subroutine is considered
  1414.       constant.)  The warning is considered    severe enough not to
  1415.       be optional because previously compiled invocations of the
  1416.       function will    still be using the old value of    the function.
  1417.       If you need to be able to redefine the subroutine you    need
  1418.       to ensure that it isn't inlined, either by dropping the ()
  1419.       prototype (which changes the calling semantics, so beware)
  1420.       or by    thwarting the inlining mechanism in some other way,
  1421.       such as
  1422.  
  1423.           sub not_inlined () {
  1424.           23 if    $];
  1425.           }
  1426.  
  1427.  
  1428.       OOOOvvvveeeerrrrrrrriiiiddddiiiinnnngggg BBBBuuuuiiiillllttttiiiinnnn FFFFuuuunnnnccccttttiiiioooonnnnssss
  1429.  
  1430.       Many builtin functions may be    overridden, though this    should
  1431.       be tried only    occasionally and for good reason.  Typically
  1432.       this might be    done by    a package attempting to    emulate
  1433.       missing builtin functionality    on a non-Unix system.
  1434.  
  1435.       Overriding may be done only by importing the name from a
  1436.       module--ordinary predeclaration isn't    good enough.  However,
  1437.       the subs pragma (compiler directive) lets you, in effect,
  1438.       predeclare subs via the import syntax, and these names may
  1439.       then override    the builtin ones:
  1440.  
  1441.           use subs 'chdir',    'chroot', 'chmod', 'chown';
  1442.           chdir $somewhere;
  1443.           sub chdir    { ... }
  1444.  
  1445.       To unambiguously refer to the    builtin    form, one may precede
  1446.  
  1447.  
  1448.  
  1449.      Page 22                        (printed 10/23/98)
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1457.  
  1458.  
  1459.  
  1460.       the builtin name with    the special package qualifier CORE::.
  1461.       For example, saying CORE::open() will    always refer to    the
  1462.       builtin open(), even if the current package has imported
  1463.       some other subroutine    called &open() from elsewhere.
  1464.  
  1465.       Library modules should not in    general    export builtin names
  1466.       like "open" or "chdir" as part of their default @EXPORT
  1467.       list,    because    these may sneak    into someone else's namespace
  1468.       and change the semantics unexpectedly.  Instead, if the
  1469.       module adds the name to the @EXPORT_OK list, then it's
  1470.       possible for a user to import    the name explicitly, but not
  1471.       implicitly.  That is,    they could say
  1472.  
  1473.           use Module 'open';
  1474.  
  1475.       and it would import the open override, but if    they said
  1476.  
  1477.           use Module;
  1478.  
  1479.       they would get the default imports without the overrides.
  1480.  
  1481.       The foregoing    mechanism for overriding builtins is
  1482.       restricted, quite deliberately, to the package that requests
  1483.       the import.  There is    a second method    that is    sometimes
  1484.       applicable when you wish to override a builtin everywhere,
  1485.       without regard to namespace boundaries.  This    is achieved by
  1486.       importing a sub into the special namespace CORE::GLOBAL::.
  1487.       Here is an example that quite    brazenly replaces the glob
  1488.       operator with    something that understands regular
  1489.       expressions.
  1490.  
  1491.           package REGlob;
  1492.           require Exporter;
  1493.           @ISA = 'Exporter';
  1494.           @EXPORT_OK = 'glob';
  1495.  
  1496.           sub import {
  1497.           my $pkg = shift;
  1498.           return unless    @_;
  1499.           my $sym = shift;
  1500.           my $where = ($sym =~ s/^GLOBAL_// ? 'CORE::GLOBAL' : caller(0));
  1501.           $pkg->export($where, $sym, @_);
  1502.           }
  1503.  
  1504.           sub glob {
  1505.           my $pat = shift;
  1506.           my @got;
  1507.           local(*D);
  1508.           if (opendir D, '.') {    @got = grep /$pat/, readdir D; closedir    D; }
  1509.           @got;
  1510.           }
  1511.           1;
  1512.  
  1513.  
  1514.  
  1515.      Page 23                        (printed 10/23/98)
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1523.  
  1524.  
  1525.  
  1526.       And here's how it could be (ab)used:
  1527.  
  1528.           #use REGlob 'GLOBAL_glob';      #    override glob()    in ALL namespaces
  1529.           package Foo;
  1530.           use REGlob 'glob';          #    override glob()    in Foo:: only
  1531.           print for    <^[a-z_]+\.pm\$>;     #    show all pragmatic modules
  1532.  
  1533.       Note that the    initial    comment    shows a    contrived, even
  1534.       dangerous example.  By overriding glob globally, you would
  1535.       be forcing the new (and subversive) behavior for the glob
  1536.       operator for eeeevvvveeeerrrryyyy namespace,    without    the complete
  1537.       cognizance or    cooperation of the modules that    own those
  1538.       namespaces.  Naturally, this should be done with extreme
  1539.       caution--if it must be done at all.
  1540.  
  1541.       The REGlob example above does    not implement all the support
  1542.       needed to cleanly override perl's glob operator.  The
  1543.       builtin glob has different behaviors depending on whether it
  1544.       appears in a scalar or list context, but our REGlob doesn't.
  1545.       Indeed, many perl builtins have such context sensitive
  1546.       behaviors, and these must be adequately supported by a
  1547.       properly written override.  For a fully functional example
  1548.       of overriding    glob, study the    implementation of
  1549.       File::DosGlob    in the standard    library.
  1550.  
  1551.       AAAAuuuuttttoooollllooooaaaaddddiiiinnnngggg
  1552.  
  1553.       If you call a    subroutine that    is undefined, you would
  1554.       ordinarily get an immediate fatal error complaining that the
  1555.       subroutine doesn't exist.  (Likewise for subroutines being
  1556.       used as methods, when    the method doesn't exist in any    base
  1557.       class    of the class package.) If, however, there is an
  1558.       AUTOLOAD subroutine defined in the package or    packages that
  1559.       were searched    for the    original subroutine, then that
  1560.       AUTOLOAD subroutine is called    with the arguments that    would
  1561.       have been passed to the original subroutine.    The fully
  1562.       qualified name of the    original subroutine magically appears
  1563.       in the $AUTOLOAD variable in the same    package    as the
  1564.       AUTOLOAD routine.  The name is not passed as an ordinary
  1565.       argument because, er,    well, just because, that's why...
  1566.  
  1567.       Most AUTOLOAD    routines will load in a    definition for the
  1568.       subroutine in    question using eval, and then execute that
  1569.       subroutine using a special form of "goto" that erases    the
  1570.       stack    frame of the AUTOLOAD routine without a    trace.    (See
  1571.       the standard AutoLoader module, for example.)     But an
  1572.       AUTOLOAD routine can also just emulate the routine and never
  1573.       define it.   For example, let's pretend that a function that
  1574.       wasn't defined should    just call system() with    those
  1575.       arguments.  All you'd    do is this:
  1576.  
  1577.  
  1578.  
  1579.  
  1580.  
  1581.      Page 24                        (printed 10/23/98)
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1589.  
  1590.  
  1591.  
  1592.           sub AUTOLOAD {
  1593.           my $program =    $AUTOLOAD;
  1594.           $program =~ s/.*:://;
  1595.           system($program, @_);
  1596.           }
  1597.           date();
  1598.           who('am',    'i');
  1599.           ls('-l');
  1600.  
  1601.       In fact, if you predeclare the functions you want to call
  1602.       that way, you    don't even need    the parentheses:
  1603.  
  1604.           use subs qw(date who ls);
  1605.           date;
  1606.           who "am",    "i";
  1607.           ls -l;
  1608.  
  1609.       A more complete example of this is the standard Shell
  1610.       module, which    can treat undefined subroutine calls as    calls
  1611.       to Unix programs.
  1612.  
  1613.       Mechanisms are available for modules writers to help split
  1614.       the modules up into autoloadable files.  See the standard
  1615.       AutoLoader module described in the _A_u_t_o_L_o_a_d_e_r    manpage    and in
  1616.       the _A_u_t_o_S_p_l_i_t    manpage, the standard SelfLoader modules in
  1617.       the _S_e_l_f_L_o_a_d_e_r manpage, and the document on adding C
  1618.       functions to perl code in the    _p_e_r_l_x_s manpage.
  1619.  
  1620.      SSSSEEEEEEEE AAAALLLLSSSSOOOO
  1621.       See the _p_e_r_l_r_e_f manpage for more about references and
  1622.       closures.  See the _p_e_r_l_x_s manpage if you'd like to learn
  1623.       about    calling    C subroutines from perl.  See the _p_e_r_l_m_o_d
  1624.       manpage to learn about bundling up your functions in
  1625.       separate files.
  1626.  
  1627.  
  1628.  
  1629.  
  1630.  
  1631.  
  1632.  
  1633.  
  1634.  
  1635.  
  1636.  
  1637.  
  1638.  
  1639.  
  1640.  
  1641.  
  1642.  
  1643.  
  1644.  
  1645.  
  1646.  
  1647.      Page 25                        (printed 10/23/98)
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654.      PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSUUUUBBBB((((1111))))
  1655.  
  1656.  
  1657.  
  1658.  
  1659.  
  1660.  
  1661.  
  1662.  
  1663.  
  1664.  
  1665.  
  1666.  
  1667.  
  1668.  
  1669.  
  1670.  
  1671.  
  1672.  
  1673.  
  1674.  
  1675.  
  1676.  
  1677.  
  1678.  
  1679.  
  1680.  
  1681.  
  1682.  
  1683.  
  1684.  
  1685.  
  1686.  
  1687.  
  1688.  
  1689.  
  1690.  
  1691.  
  1692.  
  1693.  
  1694.  
  1695.  
  1696.  
  1697.  
  1698.  
  1699.  
  1700.  
  1701.  
  1702.  
  1703.  
  1704.  
  1705.  
  1706.  
  1707.  
  1708.  
  1709.  
  1710.      Page 26                        (printed 10/23/98)
  1711.  
  1712.  
  1713.  
  1714.  
  1715.  
  1716.  
  1717.